package com.cloud.pdd.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.cloud.pdd.config.Config;
import com.cloud.pdd.model.domain.PddOrderDetailRequest;
import com.cloud.pdd.model.entity.PddFinances;
import com.cloud.pdd.model.entity.PddOrder;
import com.cloud.pdd.mapper.PddOrderMapper;
import com.cloud.pdd.model.entity.PddUserRecords;
import com.cloud.pdd.model.request.PddCenterOrderListRequest;
import com.cloud.pdd.model.request.PddOrderListRequest;
import com.cloud.pdd.service.PddFinancesService;
import com.cloud.pdd.service.PddOrderService;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloud.pdd.service.PddProductService;
import com.cloud.pdd.util.PddUtil;
import com.cloud.pdd.util.TimeHelper;
import com.pdd.pop.sdk.http.PopClient;
import com.pdd.pop.sdk.http.api.pop.request.PddDdkOrderDetailGetRequest;
import com.pdd.pop.sdk.http.api.pop.request.PddDdkOrderListIncrementGetRequest;
import com.pdd.pop.sdk.http.api.pop.response.PddDdkOrderDetailGetResponse;
import com.pdd.pop.sdk.http.api.pop.response.PddDdkOrderListIncrementGetResponse;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.stereotype.Service;
import cn.hutool.core.bean.BeanUtil;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 拼多多订单
 *
 * @author douhaichao code generator
 * @date 2021-04-14 11:10:20
 */
@Service
@AllArgsConstructor
public class PddOrderServiceImpl extends ServiceImpl<PddOrderMapper, PddOrder> implements PddOrderService {

    private final PddCommonServiceImpl pddCommonService;
    private final Config config;
    private final PddFinancesService pddFinancesService;
    private final PddProductService pddProductService;
    private final PddUtil pddUtil;

    //    https://open.pinduoduo.com/application/document/api?id=pdd.ddk.order.list.increment.get&permissionId=2
    @SneakyThrows
    @Override
    public PddDdkOrderListIncrementGetResponse getOrderListIncrement(PddOrderListRequest req) {
        PopClient client = pddCommonService.getClient();
        PddDdkOrderListIncrementGetRequest request = new PddDdkOrderListIncrementGetRequest();
//        request.setCashGiftOrder(false);
        request.setEndUpdateTime(req.getEndUpdateTime());
        request.setPage(req.getPage());
        request.setPageSize(req.getPageSize());
//        request.setQueryOrderType(0);
//        request.setReturnCount(false);
        request.setStartUpdateTime(req.getStartUpdateTime());
        PddDdkOrderListIncrementGetResponse response = client.syncInvoke(request);
        return response;
    }

    //    https://open.pinduoduo.com/application/document/api?id=pdd.ddk.order.detail.get&permissionId=2
    @SneakyThrows
    @Override
    public PddDdkOrderDetailGetResponse getOrderDetail(HttpServletRequest httpServletRequest, PddOrderDetailRequest req) {
        PopClient client = pddCommonService.getClient();
        PddDdkOrderDetailGetRequest request = new PddDdkOrderDetailGetRequest();
        request.setOrderSn(req.getOrderSn());
        request.setQueryOrderType(req.getQueryOrderType());
        PddDdkOrderDetailGetResponse response = client.syncInvoke(request);
        return response;
    }

    @Override
    public void syncOrder(Integer day) {
        //同步X天数据
        for (Integer i = day; i >= 0; i--) {
            String startTime = DateUtil.format(DateUtils.addDays(Convert.toDate(cn.hutool.core.date.DateUtil.today()), i * -1), "yyyy-MM-dd");
            syncOrderByDay(startTime);
        }

    }

    @Override
    public void syncOrderByDay(String startTime) {
        startTime = startTime + " 00:00:00";
        Date date = DateUtils.addDays(Convert.toDate(startTime), 1);

        long start = DateUtil.parse(startTime).getTime();
        long end = date.getTime();
        long getTime = DateUtil.parse("1970-01-01 08:00:00").getTime();
        start = start / 1000 - getTime;
        end = end / 1000 - getTime;
        getOrderData(start, end);
    }

    private void getOrderData(long start, long end) {
        int pagesize = 50;
        int page = 0;
        long allPageSize = 0;
        do {
            //如果 当前页小于总页就循环
            page++;
            PddOrderListRequest pddOrderListRequest = new PddOrderListRequest();
            pddOrderListRequest.setStartUpdateTime(start);
            pddOrderListRequest.setEndUpdateTime(end);
            pddOrderListRequest.setPage(page);
            pddOrderListRequest.setPageSize(pagesize);
            PddDdkOrderListIncrementGetResponse orderListIncrement = getOrderListIncrement(pddOrderListRequest);

            PddDdkOrderListIncrementGetResponse.OrderListGetResponse orderListGetResponse = orderListIncrement.getOrderListGetResponse();
            List<PddDdkOrderListIncrementGetResponse.OrderListGetResponseOrderListItem> orderList = orderListGetResponse.getOrderList();
            if (orderList != null) {
                for (PddDdkOrderListIncrementGetResponse.OrderListGetResponseOrderListItem item : orderList) {
                    PddOrder pddOrder = new PddOrder();
                    BeanUtil.copyProperties(item, pddOrder);
                    pddOrder.setOrderCreateTime(TimeHelper.toDateTime(item.getOrderCreateTime()));
                    pddOrder.setOrderGroupSuccessTime(TimeHelper.toDateTime(item.getOrderGroupSuccessTime()));
                    pddOrder.setOrderPayTime(TimeHelper.toDateTime(item.getOrderPayTime()));
                    pddOrder.setOrderReceiveTime(TimeHelper.toDateTime(item.getOrderReceiveTime()));
                    pddOrder.setOrderSettleTime(TimeHelper.toDateTime(item.getOrderSettleTime()));
                    pddOrder.setOrderVerifyTime(TimeHelper.toDateTime(item.getOrderVerifyTime()));
                    pddOrder.setUserId(getUserIdByOrder(item.getCustomParameters()));
                    BigDecimal realPayAmount = pddUtil.getProductCommission(item.getPromotionAmount());
                    pddOrder.setUserAmount(realPayAmount);
                    upsert(pddOrder);
                }
            }
            allPageSize = orderListGetResponse.getTotalCount() % pagesize > 0 ? orderListGetResponse.getTotalCount() / pagesize + 1 :
                    orderListGetResponse.getTotalCount() / pagesize;
        } while (page <= allPageSize);
    }

    //增加或修改订单信息
    private void upsert(PddOrder pddOrder) {
        String orderSn = pddOrder.getOrderSn();
        String goodsId = pddOrder.getGoodsId();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("order_sn", orderSn);
        queryWrapper.eq("goods_id", goodsId);
        Integer count = baseMapper.selectCount(queryWrapper);
        if (count == 0) {
            baseMapper.insert(pddOrder);
        } else {
            //佣金只计算一次
            pddOrder.setUserAmount(null);
            baseMapper.update(pddOrder, queryWrapper);
        }

    }

    private Integer getUserIdByOrder(String customParameters) {
        if (StrUtil.isEmpty(customParameters)) {
            return 0;
        }
        //查找所属人
        JSONObject customParametersObject = JSONUtil.parseObj(customParameters);
        if (customParametersObject == null) {
            return 0;
        }
        return Convert.toInt(customParametersObject.get("uid"), 0);
    }

    @Override
    public IPage<PddOrder> selectList(Page page, PddCenterOrderListRequest req) {
        if (req.getUserId() == null) {
            return null;
        }
//        PddOrder model = new PddOrder();
//        BeanUtil.copyProperties(req, model);
        QueryWrapper<PddOrder> queryWrapper = new QueryWrapper<PddOrder>();
        if (req.getOrderStatus() != null) {
            queryWrapper.in("order_status", req.getOrderStatus());
        }
        queryWrapper.eq("user_id", req.getUserId());
        queryWrapper.orderByDesc("id");
        IPage<PddOrder> list = baseMapper.selectPage(
                page, queryWrapper
        );
        return list;
    }

    @Transactional
    @Override
    public void pay() {
        PddOrder pddOrder = new PddOrder();
        pddOrder.setPddPayStatus(0);
        QueryWrapper queryWrapper = new QueryWrapper();
        //查询成长社区里待结算订单，拼多多已结算的订单
        queryWrapper.eq("pdd_pay_status", 0);
        queryWrapper.eq("order_status", 5);
        //查询待支付订单
        List<PddOrder> orderList = baseMapper.selectList(queryWrapper);
        for (PddOrder order : orderList) {
            //1.修改订单状态,改为已结算
            order.setPddPayStatus(1);
            int status = baseMapper.updateById(order);
            if (status <= 0) {
                continue;
            }
            //查询余额
            Integer userId = order.getUserId();
            QueryWrapper queryWrapperFinance = new QueryWrapper();
            queryWrapperFinance.eq("user_id", userId);
            PddFinances userFinances = pddFinancesService.getOne(queryWrapperFinance);
            if (userFinances == null) {
                //创建账户
                userFinances = new PddFinances();
                userFinances.setUserId(userId);
                pddFinancesService.save(userFinances);
            }
            //2.增加流水
            PddUserRecords pddUserRecords = new PddUserRecords();
            pddUserRecords.setIncome(order.getUserAmount());
            pddUserRecords.setRemark("订单收益：" + order.getOrderSn());
            BigDecimal surplus = NumberUtil.add(userFinances.getMoney(), order.getUserAmount());
            pddUserRecords.setSurplus(surplus);
            pddUserRecords.setUserId(userId);
            //3.增加余额
            userFinances.setMoney(surplus);
            pddFinancesService.update(userFinances, queryWrapperFinance);
        }
    }

    @Override
    public String getCenterOrderNav(String orderStatus) {
        StringBuilder sb = new StringBuilder();
        String statusAll = "";
        String statusPayed = "";
        String statusJs = "";
        String statusFail = "";
        if (orderStatus == null || StrUtil.isEmpty(orderStatus)) {
            statusAll = " swiper-pagination-bullet-active";
        } else if (orderStatus.contains("3")) {
            statusPayed = " swiper-pagination-bullet-active";
        } else if (orderStatus.contains("5")) {
            statusJs = " swiper-pagination-bullet-active";
        } else if (orderStatus.contains("10")) {
            statusFail = " swiper-pagination-bullet-active";
        }
        sb.append("<a href='/center/order' class=\"swiper-pagination-bullet " + statusAll + "\">全部</a>");
        sb.append("<a href='/center/order?orderStatus=0,1,2,3' class=\"swiper-pagination-bullet " + statusPayed + "\">已付款</a>");
        sb.append("<a href='/center/order?orderStatus=5' class=\"swiper-pagination-bullet " + statusJs + "\">已结算</a>");
        sb.append("<a href='/center/order?orderStatus=4,10' class=\"swiper-pagination-bullet " + statusFail + "\">失效订单</a>");

        return sb.toString();
    }
}
